#pragma once

void create_user_table(sqlite3 *db) {
    char *errMsg = 0;
    const char *sql = "CREATE TABLE IF NOT EXISTS users ("
                      "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                      "name TEXT NOT NULL, "
                      "admin INTEGER NOT NULL, "
                      "password TEXT NOT NULL UNIQUE);";

    int rc = sqlite3_exec(db, sql, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        std::cerr << "SQL error: " << errMsg << std::endl;
        sqlite3_free(errMsg);
    } else {
        std::cout << "Table created successfully" << std::endl;
    }
}

void create_time_table(sqlite3 *db) {
    char *errMsg = 0;
    const char *sql = "CREATE TABLE IF NOT EXISTS timebank ("
                      "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                      "time INTEGER NOT NULL UNIQUE);";

    int rc = sqlite3_exec(db, sql, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        std::cerr << "SQL error: " << errMsg << std::endl;
        sqlite3_free(errMsg);
    } else {
        std::cout << "Table created successfully" << std::endl;
    }
}

void insert_user(sqlite3 *db, const std::string &name, const int &admin, const std::string &password) {
    char *errMsg = 0;
    std::string sql = std::format("INSERT INTO users (name, admin, password) VALUES ('{}', '{}', '{}')", name, admin, password);
    int rc = sqlite3_exec(db, sql.c_str(), 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        std::cerr << "SQL error ->" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
}

void update_time(sqlite3 *db, const int &time) {
    char *errMsg = 0;
    std::string sql = std::format("UPDATE timebank SET time = {} WHERE id=1", time);
    int rc = sqlite3_exec(db, sql.c_str(), 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        std::cerr << "SQL error ->" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
}

sqlite3_stmt* get_user(sqlite3 *db, const std::string &name) {
    char *errMsg = 0;
    sqlite3_stmt *stmt;  // 预处理语句对象
    std::string sql = std::format("SELECT * FROM users WHERE name='{}'", name);
    
    int rc = sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "预处理语句失败: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
    }
    return stmt;
}


sqlite3_stmt* get_time(sqlite3 *db) {
    char *errMsg = 0;
    sqlite3_stmt *stmt;  // 预处理语句对象
    std::string sql = std::format("SELECT * FROM timebank WHERE id=1");
    
    int rc = sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "预处理语句失败: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
    }
    return stmt;
}
